package com.warrior.util;

import com.warrior.controller.TeamController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Shawn on 2017/3/17.
 */
public class UploadUtils {


    private static final Logger logger = LogManager.getLogger(UploadUtils.class.getName());


    /**
     * saveFileToServer 上传文件保存到服务器
     *@param  request
     * @param filePath 为上传文件的名称
     *            ，
     * @param saveFilePathName 为文件保存全路径
     * @param saveFileName 为保存的文件
     * @param extendes 为允许的文件扩展名
     *            , *
     * @return 返回一个map，map中有4个值，第一个为保存的文件名fileName,第二个为保存的文件大小fileSize,,
     *         第三个为保存文件时错误信息errors,如果生成缩略图则map中保存smallFileName，表示缩略图的全路径
     */
    public static Map saveFileToServer(HttpServletRequest request,
                                       String filePath, String saveFilePathName, String saveFileName,
                                       String[] extendes) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
                .getFile(filePath);
        Map map = new HashMap();
        if (file != null && !file.isEmpty()) {
            logger.debug("文件名为：" + file.getOriginalFilename());
            /* 获取扩展名 */
            String extend = file.getOriginalFilename()
                    .substring(file.getOriginalFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (saveFileName == null || saveFileName.trim().equals("")) {
                saveFileName = UUID.randomUUID().toString() + "." + extend;
            }
            if (saveFileName.lastIndexOf(".") < 0) {
                saveFileName = saveFileName + "." + extend;
            }
            float fileSize = (float) file.getSize();// 返回文件大小，单位为k
            List<String> errors = new ArrayList<>();
            boolean flag = true;
            if (extendes == null) {
                extendes = new String[] { "jpg", "jpeg", "gif", "bmp", "tbi",
                        "png" };
            }
            for (String s : extendes) {
                if (extend.toLowerCase().equals(s))
                    flag = true;
            }
            if (flag) {
                File path = new File(saveFilePathName);
                if (!path.exists()) {
                    path.mkdir();
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                DataOutputStream out = new DataOutputStream(
                        new FileOutputStream(saveFilePathName + File.separator
                                + saveFileName));
                InputStream is = null;
                try {
                    is = file.getInputStream();
                    int size = (int) (fileSize);
                    byte[] buffer = new byte[size];
                    while (is.read(buffer) > 0) {
                        out.write(buffer);
                    }
                } catch (IOException exception) {
                    exception.printStackTrace();
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                }
                if (isImg(extend)) {
                    File img = new File(saveFilePathName + File.separator
                            + saveFileName);
                    try {
                        BufferedImage bis = ImageIO.read(img);
                        int w = bis.getWidth();
                        int h = bis.getHeight();
                        map.put("width", w);
                        map.put("height", h);
                    } catch (Exception e) {
                        // map.put("width", 200);
                        // map.put("heigh", 100);
                    }
                }
                map.put("mime", extend);
                map.put("fileName", saveFileName);
                map.put("fileSize", fileSize);
                map.put("error", errors);
                map.put("oldName", file.getOriginalFilename());
               logger.debug("上传结束，生成的文件名为:" + saveFileName);
            } else {
                // System.out.println("不允许的扩展名");
                errors.add("不允许的扩展名");
            }

        } else {
            map.put("width", 0);
            map.put("height", 0);
            map.put("mime", "");
            map.put("fileName", "");
            map.put("fileSize", 0.0f);
            map.put("oldName", "");
        }
        return map;
    }

    public static boolean isImg(String extend) {
        boolean ret = false;
        List<String> list = new ArrayList<>();
        list.add("jpg");
        list.add("jpeg");
        list.add("bmp");
        list.add("gif");
        list.add("png");
        list.add("tif");
        list.add("tbi");
        for (String s : list) {
            if (s.equals(extend))
                ret = true;
        }
        return ret;
    }

}
